#!/usr/bin/python2.4
#
# Copyright 2011 Google Inc. All Rights Reserved.

import controllers
import logging
import urllib
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

import re
import StringIO
import zipfile

def loadClouds():

  # determine current version
  fp = urllib.urlopen("http://mw1.google.com/mw-weather/clouds/root.kmz")
  z = zipfile.ZipFile(StringIO.StringIO(fp.read()))
  contents = z.read('doc.kml')
  m = re.match(r"<kml><NetworkLink><Link><href>([^/]+)/root.kmz</href></Link></NetworkLink></kml>", contents)
  return open("qld.kml").read().replace('${XXX}', m.group(1))

class GetPage(webapp.RequestHandler):
  def get(self):
    self.response.headers['Content-Type'] = 'application/vnd.google-earth.kml+xml'
    self.response.out.write(loadClouds())

application = webapp.WSGIApplication([('/clouds/qld.kml', GetPage)
                                      ], debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  loadClouds()
